﻿// -----------------------------------------------------------------------
// <copyright file="PushCountRepository.cs" company="Zen Design Corp">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Zen.BlackBerry.Push.Repositories
{
	using System;
	using System.Linq;
	using Zen.BlackBerry.Push.Count;
	using Zen.BlackBerry.Push.DataAccess;

	/// <summary>
	/// TODO: Update summary.
	/// </summary>
	public class PushCountRepository : Repository, IPushCountRepository
	{
		#region IPushCountRepository Members

		public void Add(string pushId)
		{
			DbPushRequest dbRequest = ObjectContext.DbPushRequests
				.Include("RequestCount")
				.FirstOrDefault((item) => item.PushId == pushId);
			if (dbRequest == null)
			{
				throw new ArgumentException(string.Format(
					"Request not found. Push-id={0}", pushId), "pushId");
			}

			if (dbRequest.RequestCount != null)
			{
				throw new InvalidOperationException(string.Format(
					"Request already has count tracking entry. Push-id={0}", pushId));
			}

			dbRequest.RequestCount = new DbPushRequestCount();
			ObjectContext.SaveChanges();
		}

		public bool Increment(string pushId, int amount, int max)
		{
			DbPushRequest dbRequest = ObjectContext.DbPushRequests
				.Include("RequestCount")
				.FirstOrDefault((item) => item.PushId == pushId);
			if (dbRequest == null)
			{
				throw new ArgumentException(string.Format(
					"Request not found. Push-id={0}", pushId), "pushId");
			}
			if(dbRequest.RequestCount == null)
			{
				throw new InvalidOperationException(string.Format(
					"Request is not enabled for count tracking. Push-id={0}", pushId));
			}

			if (dbRequest.RequestCount.CompletedCount < max)
			{
				dbRequest.RequestCount.CompletedCount +=
					Math.Min(amount, max - dbRequest.RequestCount.CompletedCount);
				ObjectContext.SaveChanges();
			}

			return (dbRequest.RequestCount.CompletedCount >= max);
		}

		public void Remove(string pushId)
		{
			DbPushRequest dbRequest = ObjectContext.DbPushRequests
				.Include("RequestCount")
				.FirstOrDefault((item) => item.PushId == pushId);
			if (dbRequest == null)
			{
				throw new ArgumentException(string.Format(
					"Request not found. Push-id={0}", pushId), "pushId");
			}

			if (dbRequest.RequestCount == null)
			{
				throw new InvalidOperationException(string.Format(
					"Request is not enabled count tracking. Push-id={0}", pushId));
			}

			ObjectContext.DbPushRequestCounts.DeleteObject(dbRequest.RequestCount);
			dbRequest.RequestCount = null;
			ObjectContext.SaveChanges();
		}

		#endregion
	}
}
